package com.hafu.dao;

import com.hafu.model.Course;
import com.hafu.util.DbUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CourseDao {
    private static Connection conn;
    // 数据库连接对象（非静态，每个实例独立管理）
    // 构造方法初始化连接
    public CourseDao() {
        conn = DbUtil.getConn();
    }

    /**
     * 获取所有课程（实例方法，避免静态上下文问题）
     */
    public List<Course> getAllCourses() {
        List<Course> courses = new ArrayList<>();
        String sql = "SELECT * FROM course";

        try (PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                courses.add(buildCourseFromResultSet(rs));
            }
        } catch (SQLException e) {
            handleSQLException("获取所有课程失败", e);
        }

        return courses;
    }

    /**
     * 获取学生可选的课程（未选且已发布）
     */
    public static List<Course> getAvailableCoursesForStudent(String studentId) {
        List<Course> courses = new ArrayList<>();
        String sql = "SELECT c.* FROM course c " +
                "WHERE c.status = '已发布' " +
                "AND c.course_id NOT IN (SELECT course_id FROM enrollment WHERE student_id = ?)";

        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, studentId);

            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    courses.add(buildCourseFromResultSet(rs));
                }
            }
        } catch (SQLException e) {
            handleSQLException("获取学生可选课程失败", e);
        }

        return courses;
    }

    /**
     * 搜索学生可选的课程
     */
    public static List<Course> searchAvailableCoursesForStudent(String studentId, String keyword) {
        List<Course> courses = new ArrayList<>();
        String sql = "SELECT c.* FROM course c " +
                "WHERE c.status = '已发布' " +
                "AND c.course_id NOT IN (SELECT course_id FROM enrollment WHERE student_id = ?) " +
                "AND (c.course_name LIKE ? OR c.course_id LIKE ?)";

        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, studentId);
            pstmt.setString(2, "%" + keyword + "%");
            pstmt.setString(3, "%" + keyword + "%");

            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    courses.add(buildCourseFromResultSet(rs));
                }
            }
        } catch (SQLException e) {
            handleSQLException("搜索学生可选课程失败", e);
        }

        return courses;
    }

    /**
     * 获取所有已发布课程
     */
    public List<Course> getAllPublishedCourses() {
        List<Course> courses = new ArrayList<>();
        String sql = "SELECT * FROM course WHERE status = '已发布'";

        try (PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                courses.add(buildCourseFromResultSet(rs));
            }
        } catch (SQLException e) {
            handleSQLException("获取已发布课程失败", e);
        }

        return courses;
    }

    /**
     * 教师创建课程
     */
    public boolean createCourse(Course course) {
        String sql = "INSERT INTO course " +
                "(course_id, course_name, teacher_id, credits, hours, status, create_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, NOW())";

        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, course.getCourseId());
            pstmt.setString(2, course.getCourseName());
            pstmt.setString(3, course.getTeacherId());
            pstmt.setInt(4, (Integer) course.getCredits());   // 无需强制转换
            pstmt.setInt(5, (Integer) course.getHours());     // 无需强制转换
            pstmt.setString(6, (String) course.getStatus()); // 无需强制转换

            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            handleSQLException("创建课程失败", e);
            return false;
        }
    }

    /**
     * 更新课程状态（用于审核流程）
     */
    public boolean updateCourseStatus(String courseId, String status) {
        String sql = "UPDATE course SET status = ? WHERE course_id = ?";

        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, status);
            pstmt.setString(2, courseId);

            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            handleSQLException("更新课程状态失败", e);
            return false;
        }
    }

    /**
     * 根据教师ID获取课程列表
     */
    public List<Course> getCoursesByTeacherId(String teacherId) {
        List<Course> courses = new ArrayList<>();
        String sql = "SELECT * FROM course WHERE teacher_id = ?";

        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, teacherId);

            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    courses.add(buildCourseFromResultSet(rs));
                }
            }
        } catch (SQLException e) {
            handleSQLException("根据教师ID获取课程失败", e);
        }

        return courses;
    }

    /**
     * 删除课程
     */
    public boolean deleteCourse(String courseId) {
        String sql = "DELETE FROM course WHERE course_id = ?";

        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, courseId);

            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            handleSQLException("删除课程失败", e);
            return false;
        }
    }

    // 辅助方法：从ResultSet构建Course对象
    private static Course buildCourseFromResultSet(ResultSet rs) throws SQLException {
        return new Course(
                rs.getString("course_id"),
                rs.getString("course_name"),
                rs.getString("teacher_id"),
                rs.getInt("credits"),
                rs.getInt("hours"),
                rs.getString("status"),
                rs.getString("create_time")
        );
    }

    // 辅助方法：统一处理SQL异常
    private static void handleSQLException(String operation, SQLException e) {
        System.err.println(operation + ": " + e.getMessage());
        e.printStackTrace();
    }

    public List<Course> getCoursesByStudentId(String studentId) {
        return null;
    }
}